/**
 * 文档详情组件
 */

import { useEffect, useCallback } from 'react';
import {
  FileText,
  Download,
  Heart,
  Pin,
  Plus,
  TagIcon,
  Link,
  X,
} from 'lucide-react';
import { useDocument } from '@/contexts/document';
import { showMessage } from '@/components/common/MessageTip';
import FileTypeIcon from './FileTypeIcon';
import { getBaseURL } from '@/utils/utils';

interface DocumentDetailProps {
  className?: string;
}

// 日期格式化函数已移除，因为不再需要显示日期时间

export default function DocumentDetail({ className = '' }: DocumentDetailProps) {
  const { 
    selectedDocumentId,
    selectedDocument,
    documentRelations,
    loading,
    fetchDocumentDetail,
    fetchDocumentRelations,
    toggleFavorite,
    togglePin
  } = useDocument();

  // 加载文档详情
  const loadDocumentDetail = useCallback(async (documentId: string) => {
    try {
      // 并行加载文档详情和关联关系
      await Promise.all([
        fetchDocumentDetail(documentId),
        fetchDocumentRelations(documentId),
      ]);
    } catch (error) {
      showMessage('error', '加载文档详情失败');
      console.error('Failed to load document detail:', error);
    }
  }, [fetchDocumentDetail, fetchDocumentRelations]);

  // 监听选中文档变化
  useEffect(() => {
    if (selectedDocumentId) {
      loadDocumentDetail(selectedDocumentId);
    }
  }, [selectedDocumentId, loadDocumentDetail]);

  // 切换收藏状态
  const handleToggleFavorite = useCallback(async () => {
    if (!selectedDocument) return;
    
    try {
      await toggleFavorite(selectedDocument.id);
      const newFavoriteState = !selectedDocument.is_favorite;
      showMessage('success', newFavoriteState ? '已添加到收藏' : '已取消收藏');
    } catch (error) {
      showMessage('error', '操作失败');
      console.error('Failed to toggle favorite:', error);
    }
  }, [selectedDocument, toggleFavorite]);

  // 切换置顶状态
  const handleTogglePin = useCallback(async () => {
    if (!selectedDocument) return;
    
    try {
      await togglePin(selectedDocument.id);
      const newPinState = !selectedDocument.is_pinned;
      showMessage('success', newPinState ? '已置顶' : '已取消置顶');
    } catch (error) {
      showMessage('error', '操作失败');
      console.error('Failed to toggle pin:', error);
    }
  }, [selectedDocument, togglePin]);



  // 下载文档
  const handleDownload = useCallback(() => {
    if (!selectedDocument) return;
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = `${getBaseURL()}/personal-documents/${selectedDocument.id}/download`;
    link.download = selectedDocument.filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }, [selectedDocument]);

  if (!selectedDocumentId) {
    return (
      <div className={`flex flex-col items-center justify-center h-full text-center ${className}`}>
        <FileText className="w-16 h-16 text-muted mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">选择文档</h3>
        <p className="text-muted-foreground">
          从左侧列表中选择一个文档查看详情
        </p>
      </div>
    );
  }

  if (loading.document) {
    return (
      <div className={`flex items-center justify-center h-full ${className}`}>
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  if (!selectedDocument) {
    return (
      <div className={`flex flex-col items-center justify-center h-full text-center ${className}`}>
        <FileText className="w-16 h-16 text-muted mb-4" />
        <h3 className="text-lg font-medium text-foreground mb-2">加载失败</h3>
        <p className="text-muted-foreground">
          无法加载文档详情，请重试
        </p>
      </div>
    );
  }

  const currentDocument = selectedDocument;

  return (
    <div className={`h-full flex flex-col ${className}`}>
      {/* 文档基本信息 */}
      <div className="p-4 border-b border-border">
        {/* 文档头部 */}
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-start space-x-3 flex-1">
            <FileTypeIcon fileType={currentDocument.file_type} size="lg" />
            <div className="flex-1 min-w-0">
              <h2 title={currentDocument.title} className="text-base font-semibold text-foreground mb-1 line-clamp-3 break-words">
                {currentDocument.title}
              </h2>
              <p title={currentDocument.filename} className="text-xs text-muted-foreground line-clamp-3 break-words">
                {currentDocument.filename}
              </p>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex items-center space-x-2">

            <button
              onClick={handleDownload}
              className="w-8 h-8 flex items-center justify-center rounded hover:bg-accent transition-colors"
              title="下载"
            >
              <Download className="w-4 h-4 text-muted-foreground" />
            </button>
            <button
              onClick={handleToggleFavorite}
              className="w-8 h-8 flex items-center justify-center rounded hover:bg-accent transition-colors"
              title={currentDocument.is_favorite ? '取消收藏' : '收藏'}
            >
              <Heart
                className={`w-4 h-4 ${currentDocument.is_favorite ? 'fill-destructive text-destructive' : 'text-muted-foreground'}`}
              />
            </button>
            <button
              onClick={handleTogglePin}
              className="w-8 h-8 flex items-center justify-center rounded hover:bg-accent transition-colors"
              title={currentDocument.is_pinned ? '取消置顶' : '置顶'}
            >
              <Pin
                className={`w-4 h-4 ${currentDocument.is_pinned ? 'text-primary' : 'text-muted-foreground'}`}
                style={{ transform: 'rotate(45deg)' }}
              />
            </button>
          </div>
        </div>

        {/* 文档描述 */}
        <div className="mb-4">
          <label className="block text-sm font-medium text-foreground mb-2">描述</label>
          <p className="text-sm text-muted-foreground">
            {currentDocument.description || '暂无描述'}
          </p>
        </div>

        {/* 文档元数据 - 只保留分类 */}
        <div className="text-sm">
          <div>
            <span className="text-muted-foreground">分类:</span>
            <span className="ml-2 text-foreground">
              {currentDocument.category ? (
                <span className="inline-flex items-center">
                  {currentDocument.category.icon && <span className="mr-1">{currentDocument.category.icon}</span>}
                  {currentDocument.category.name}
                </span>
              ) : (
                '未分类'
              )}
            </span>
          </div>
        </div>
      </div>

      {/* 标签区域 */}
      <div className="p-4 border-b border-border">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-medium text-foreground">标签</h3>
          <button
            className="w-6 h-6 flex items-center justify-center rounded hover:bg-accent transition-colors"
            title="添加标签"
          >
            <Plus className="w-4 h-4 text-muted-foreground" />
          </button>
        </div>
        
        {currentDocument.tags.length > 0 ? (
          <div className="flex flex-wrap gap-2">
            {currentDocument.tags.map((tag: any) => (
              <span
                key={tag.id}
                className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-accent text-foreground group"
                style={{ backgroundColor: tag.color ? `${tag.color}20` : undefined }}
              >
                <TagIcon className="w-3 h-3 mr-1" />
                {tag.name}
                <button
                  className="ml-1 w-3 h-3 flex items-center justify-center rounded-full hover:bg-muted opacity-0 group-hover:opacity-100 transition-opacity"
                  title="移除标签"
                >
                  <X className="w-2 h-2" />
                </button>
              </span>
            ))}
          </div>
        ) : (
          <p className="text-sm text-muted-foreground">暂无标签</p>
        )}
      </div>

      {/* 关联的检查项 */}
      <div className="flex-1 overflow-y-auto">
        <div className="p-4">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-sm font-medium text-foreground">关联的检查项</h3>
            <button
              className="w-6 h-6 flex items-center justify-center rounded hover:bg-accent transition-colors"
              title="添加关联"
            >
              <Plus className="w-4 h-4 text-muted-foreground" />
            </button>
          </div>

          {loading.relations ? (
            <div className="flex items-center justify-center py-8">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
            </div>
          ) : documentRelations.length > 0 ? (
            <div className="space-y-3">
              {documentRelations.map((relation: any) => (
                <div
                  key={relation.id}
                  className="flex items-start justify-between p-3 bg-muted rounded-lg"
                >
                  <div className="flex-1">
                    <div className="flex items-center space-x-2 mb-1">
                      <Link className="w-4 h-4 text-muted-foreground" />
                      <span className="text-sm font-medium text-foreground">
                        {relation.compliance_item?.title || '检查项'}
                      </span>
                      <span className={`px-2 py-0.5 rounded text-xs font-medium ${
                        relation.relation_type === 'evidence' 
                          ? 'bg-[hsl(var(--tag-active-bg))] text-[hsl(var(--tag-active-text))]'
                          : relation.relation_type === 'reference'
                          ? 'bg-[hsl(var(--tag-pending-bg))] text-[hsl(var(--tag-pending-text))]'
                          : 'bg-[hsl(var(--tag-medium-bg))] text-[hsl(var(--tag-medium-text))]'
                      }`}>
                        {relation.relation_type === 'evidence' ? '证据' : 
                         relation.relation_type === 'reference' ? '参考' : '模板'}
                      </span>
                    </div>
                    {relation.description && (
                      <p className="text-xs text-muted-foreground ml-6">
                        {relation.description}
                      </p>
                    )}
                  </div>
                  <button
                    className="w-6 h-6 flex items-center justify-center rounded hover:bg-accent transition-colors"
                    title="移除关联"
                  >
                    <X className="w-3 h-3 text-muted-foreground" />
                  </button>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8">
              <Link className="w-12 h-12 text-muted mx-auto mb-3" />
              <p className="text-sm text-muted-foreground">暂无关联的检查项</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
